package com.kdgc.power.fw.bean;

import com.kdgc.power.common.util.StringUtil;
import com.kdgc.power.fw.annotation.Code;
import com.kdgc.power.fw.annotation.CreateTime;
import lombok.Data;
import org.beetl.sql.annotation.builder.UpdateTime;
import org.beetl.sql.annotation.entity.AutoID;
import org.springframework.format.annotation.DateTimeFormat;

import java.lang.reflect.Field;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Data
public class BaseEntity {
    private String isUse;
    @CreateTime
    @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")
    private Date createTime;
    @UpdateTime
    @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")
    private Date modifyTime;

    /**
     * 获取实体类的主键对应数据库字段
     */
    public String getAutoFieldName() {
        Field[] declaredFields = getClass().getDeclaredFields();
        String keyName = null;
        for (Field field : declaredFields) {
            AutoID tableId = field.getAnnotation(AutoID.class);
            if (StringUtil.isNotEmpty(tableId)) {
                keyName =  field.getName();
                break;
            }
        }
        return keyName;
    }
    /**
     * 获取实体类的主键对应数据库字段
     */
    public String getCodeFieldName() {
        Field[] declaredFields = getClass().getDeclaredFields();
        String keyName = null;
        for (Field field : declaredFields) {
            Code tableId = field.getAnnotation(Code.class);
            if (StringUtil.isNotEmpty(tableId)) {
                keyName =  field.getName();
                break;
            }
        }
        return keyName;
    }
    public Map<String,Object>getCodeInfo(){
        Map<String,Object> codeInfo=new HashMap<>();
        Field[] declaredFields = getClass().getDeclaredFields();
        for (Field field : declaredFields) {
            Code tableId = field.getAnnotation(Code.class);
            if (StringUtil.isNotEmpty(tableId)) {
                codeInfo.put("fileName",field.getName());
                codeInfo.put("prefix",tableId.prefix());
                codeInfo.put("length",tableId.length());
                break;
            }
        }
        return codeInfo;
    }
}
